package cn.edu.xcu.ckl.fragment;

import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;

import com.lzy.okgo.OkGo;

import java.util.ArrayList;
import java.util.List;

import cn.edu.xcu.ckl.R;
import cn.edu.xcu.ckl.adapter.CarListAdapter;
import cn.edu.xcu.ckl.api.ApiConstants;
import cn.edu.xcu.ckl.base.BaseFragment;
import cn.edu.xcu.ckl.entity.CarInfo;
import cn.edu.xcu.ckl.entity.CarListInfo;
import cn.edu.xcu.ckl.entity.OrderInfo;
import cn.edu.xcu.ckl.entity.OrderListInfo;
import cn.edu.xcu.ckl.entity.ProductInfo;
import cn.edu.xcu.ckl.entity.UserInfo;
import cn.edu.xcu.ckl.http.HttpStringCallback;
import cn.edu.xcu.ckl.utils.GsonUtils;


public class ShoppingCartFragment extends BaseFragment {
    private RecyclerView recyclerView;
    private TextView total;
    private TextView btn_total;

    private CarListAdapter mCarListAdapter;

    private List<OrderInfo> mOrderInfoList = new ArrayList<>();

    private  AlertDialog mAlertDialog;



    @Override
    protected int getContentView() {
        return R.layout.fragment_shopping_cart;
    }

    @Override
    protected void initView() {
        //初始化控件
        recyclerView = rootView.findViewById(R.id.recyclerView);
        total = rootView.findViewById(R.id.total);
        btn_total = rootView.findViewById(R.id.btn_total);
    }

    @Override
    protected void setListener() {
        //初始化mCarListAdapter
        mCarListAdapter = new CarListAdapter(getActivity());
        //设置适配器
        recyclerView.setAdapter(mCarListAdapter);

        //recyclerView点击事件
        mCarListAdapter.setOnItemClickListener(new CarListAdapter.onItemClickListener() {
            @Override
            public void onPlusOnClick(CarInfo carInfo, int position) {
                //加购商品
                ProductInfo productInfo = new ProductInfo();
                productInfo.setProduct_id(carInfo.getProduct_id());
                productInfo.setProduct_img(carInfo.getProduct_img());
                productInfo.setProduct_title(carInfo.getProduct_title());
                productInfo.setProduct_price(carInfo.getProduct_price());

                addCar(productInfo);

            }

            @Override
            public void onSubTractOnClick(CarInfo carInfo, int position) {
                //减购商品
                subTractCar(carInfo);
            }

            @Override
            public void delOnClick(CarInfo carInfo, int position) {
                new AlertDialog.Builder(getActivity())
                        .setTitle("温馨提示")
                        .setMessage("确认是否要删除商品")
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                delCarById(carInfo.getCar_id());
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).show();

            }
        });


        //结算支付
        btn_total.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<CarInfo> carInfoList = mCarListAdapter.getCarInfoList();
                if (carInfoList.size() == 0) {
                    showToast("您还没有选购商品～");
                } else {
                    View view = LayoutInflater.from(getActivity()).inflate(R.layout.pay_dialog_layout, null);
                    TextView tv_total = view.findViewById(R.id.tv_total);
                    Button mr_submit = view.findViewById(R.id.mr_submit);
                    TextView mr_cancel = view.findViewById(R.id.mr_cancel);
                    //设置总的价格
                    tv_total.setText(total.getText().toString());
                    mr_submit.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //下单
                            mOrderInfoList.clear();
                            List<CarInfo> carInfos = mCarListAdapter.getCarInfoList();
                            for (int i = 0; i < carInfos.size(); i++) {
                                CarInfo carInfo = carInfos.get(i);
                                //赋值给订单
                                OrderInfo orderInfo = new OrderInfo();
                                orderInfo.setAddress("");
                                orderInfo.setMobile("");
                                orderInfo.setProduct_img(carInfo.getProduct_img());
                                orderInfo.setProduct_title(carInfo.getProduct_title());
                                orderInfo.setProduct_price(carInfo.getProduct_price());
                                orderInfo.setProduct_count(carInfo.getProduct_count());
                                orderInfo.setUsername(carInfo.getUsername());
                                mOrderInfoList.add(orderInfo);
                            }

                            //合并成集合
                            OrderListInfo orderListInfo = new OrderListInfo();
                            orderListInfo.setList(mOrderInfoList);
                            createOrder(orderListInfo);
                        }
                    });
                    //取消
                    mr_cancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (null!=mAlertDialog){
                                mAlertDialog.dismiss();
                            }
                        }
                    });
                    mAlertDialog = new AlertDialog.Builder(getActivity()).create();
                    mAlertDialog.setTitle("支付温馨提示");
                    mAlertDialog.setView(view);
                    mAlertDialog.show();
                }

            }
        });
    }

    @Override
    protected void initData() {
        queryCarByUsername();
    }

    public void loadData() {

        queryCarByUsername();
    }

    private void subTractCar(CarInfo carInfo) {
        OkGo.<String>get(ApiConstants.SUB_TRACT_CAR_URL)
                .params("username", UserInfo.getUserInfo().getUsername())
                .params("product_id", carInfo.getProduct_id())
                .execute(new HttpStringCallback(null) {
                    @Override
                    protected void onSuccess(String msg, String response) {
                        loadData();
                    }

                    @Override
                    protected void onError(String response) {
                        showToast(response);
                    }
                });

    }

    @Override
    public void onResume() {
        super.onResume();
        queryCarByUsername();
    }

    /**
     * 创建订单
     */

    private void createOrder(OrderListInfo orderListInfo) {
        OkGo.<String>post(ApiConstants.CREATE_ORDER_URL)
                .params("json", GsonUtils.toJsonString(orderListInfo))
                .execute(new HttpStringCallback(null) {
                    @Override
                    protected void onSuccess(String msg, String response) {
                        showToast(msg);
                        if (null!=mAlertDialog){
                            mAlertDialog.dismiss();
                        }
                        //清空购物车
                        clearCarByUsername();
                    }

                    @Override
                    protected void onError(String response) {

                    }
                });
    }

    /**
     * 批量删除购物车
     */
    private void clearCarByUsername() {
        if (mCarListAdapter == null) {
            return;
        }

        CarListInfo carListInfo = new CarListInfo(mCarListAdapter.getCarInfoList());
        OkGo.<String>post(ApiConstants.CLEAR_CAR_BY_USERNAME_URL)
                .params("json", GsonUtils.toJsonString(carListInfo))
                .execute(new HttpStringCallback(null) {
                    @Override
                    protected void onSuccess(String msg, String response) {
                        loadData();
                    }

                    @Override
                    protected void onError(String response) {

                    }
                });


    }


    /**
     * 根据用户名查询购物车
     */
    private void queryCarByUsername() {
        UserInfo userInfo = UserInfo.getUserInfo();
        if (userInfo != null) {
            OkGo.<String>get(ApiConstants.QUERY_CAR_BY_USERNAME_URL)
                    .params("username", UserInfo.getUserInfo().getUsername())
                    .execute(new HttpStringCallback(null) {
                        @Override
                        protected void onSuccess(String msg, String response) {
                            CarListInfo carListInfo = GsonUtils.parseJson(response, CarListInfo.class);
                            if (null != mCarListAdapter) {
                                mCarListAdapter.setCarInfoList(carListInfo.getList());
                            }
                            setTotalData(mCarListAdapter.getCarInfoList());
                        }

                        @Override
                        protected void onError(String response) {

                        }
                    });
        }
    }


    /**
     * 删除购物车
     */
    private void delCarById(int car_id) {
        OkGo.<String>get(ApiConstants.DEL_CAR_BY_ID_URL)
                .params("car_id", car_id)
                .execute(new HttpStringCallback(null) {
                    @Override
                    protected void onSuccess(String msg, String response) {
                        showToast(msg);
                        queryCarByUsername();
                    }

                    @Override
                    protected void onError(String response) {

                    }
                });
    }


    /**
     * 合计
     */
    private void setTotalData(List<CarInfo> list) {
        int toTalCount = 0;
        for (int i = 0; i < list.size(); i++) {
            int price = list.get(i).getProduct_price() * list.get(i).getProduct_count();
            toTalCount = toTalCount + price;
        }
        //设置数据
        total.setText(toTalCount + ".00");

    }

    /**
     * 加入购物车
     */
    private void addCar(ProductInfo productInfo) {
        OkGo.<String>get(ApiConstants.ADD_CAR_URL)
                .params("username", UserInfo.getUserInfo().getUsername())
                .params("product_id", productInfo.getProduct_id())
                .params("product_img", productInfo.getProduct_img())
                .params("product_title", productInfo.getProduct_title())
                .params("product_price", productInfo.getProduct_price())
                .params("product_count", 1)
                .execute(new HttpStringCallback(null) {
                    @Override
                    protected void onSuccess(String msg, String response) {
                        loadData();
                    }

                    @Override
                    protected void onError(String response) {

                    }
                });

    }


}